package web.servlet;

import domain.Account;
import domain.Product;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import service.AccountService;
import service.CatelogService;

import java.io.IOException;
import java.util.List;

public class RegisterServlet extends HttpServlet {
    private static final String REGISTER_FORM = "/WEB-INF/jsp/account/register.jsp";
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/signon.jsp";

    private String username;
    private String password;
    private String repeat_password;

    private String r_msg;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.username = req.getParameter("username");
        this.password = req.getParameter("password");
        this.repeat_password = req.getParameter("repeat_password");

        //校验用户输入的正确性
        if (!validate()){
            req.setAttribute("RegisterMsg",this.r_msg);
            req.getRequestDispatcher(REGISTER_FORM).forward(req,resp);
        }
        else {
            AccountService accountService = new AccountService();
            Account newAccount = new Account();
            newAccount.setUsername(username);
            newAccount.setPassword(password);

            accountService.insertAccount(newAccount);
            req.getRequestDispatcher(SIGNON_FORM).forward(req,resp);
        }
    }

    private boolean validate(){
        if (this.username == null || this.username.equals("")){
            this.r_msg  = "用户名不能为空";
            return false;
        }
        if (this.password == null || this.password.equals("")){
            this.r_msg = "密码不能为空";
            return false;
        }
        if (this.repeat_password == null || !this.repeat_password.equals(password)){
            this.r_msg = "请重新确认密码";
            return false;
        }
        return true;
    }
}
